package com.itemp.ms66btreceiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;

public class MountReceiver extends BroadcastReceiver {
    private String TAG = "ms66btreceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        if (Intent.ACTION_MEDIA_MOUNTED.equals(intent.getAction())){
            String mountPath = intent.getData().getPath();
            Log.d(TAG, "mountPath = " + mountPath);
            File wifiConfigFile = new File(mountPath, "wifi.config");
            if(wifiConfigFile.exists()){
                String wifiConfig = readFile(wifiConfigFile.getAbsolutePath());
                //"WIFI_SSID;password123456"
                Log.d(TAG, "wifiConfig:" + wifiConfig);
                if(!TextUtils.isEmpty(wifiConfig)){
                    String[]arrs = wifiConfig.split(";");
                    if(arrs != null && arrs.length > 1){
                        String SSID = arrs[0];
                        String password = arrs[1];
                        Log.d(TAG, "WIFI CONFIG: " + SSID + "\n" + password);
                        Intent intent1 = new Intent(context, MainActivity.class);
                        intent1.putExtra("ssid", SSID);
                        intent1.putExtra("password",password);
                        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        context.startActivity(intent1);
                    }
                }
            }
        }
    }

    private  String readFile(String filePathName) {
        StringBuffer stringBuffer = new StringBuffer();
        FileInputStream fileInputStream;
        try {
            fileInputStream = new FileInputStream(filePathName);
            byte[] buffer = new byte[1024];
            int len = fileInputStream.read(buffer);
            while (len > 0) {
                stringBuffer.append(new String(buffer, 0, len));
                len = fileInputStream.read(buffer);
            }
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuffer.toString();
    }

}